package net.sudot.chess.business.dto;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.lang.reflect.Field;

/**
 * 反射字段
 *
 * @author tangjialin on 2018-04-15.
 */
@Getter
@Setter
@Accessors(chain = true)
public class ReflectFieldDTO implements Serializable {
    private Object target;
    private Field field;
    private Object value;

    public ReflectFieldDTO(Object target, Field field) {
        this.target = target;
        this.field = field;
    }

    public Object getValue() {
        if (value != null) {
            try {
                value = field.get(getTarget());
            } catch (IllegalAccessException e) {
                throw new RuntimeException("取值错误:" + field.getName(), e);
            }
        }
        return value;
    }

    public ReflectFieldDTO setValue(Object value) {
        this.value = value;
        try {
            field.set(getTarget(), value);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("赋值错误:" + field.getName(), e);
        }
        return this;
    }
}
